package edu.sctu;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018-5-24.
 */
public class Database {

    public boolean login(String username, String password)
            throws SQLException, ClassNotFoundException {


        boolean isLogin = false;

        String sql = "select count(*) from t_users where username='" + username + "' and password = '" + password + "'";

        Connection connection = getConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);

        int count = 0;
        while (resultSet.next()){

            count = resultSet.getInt(1);
        }

        if (count != 0)
            isLogin = true;

        return isLogin;

    }

    public List<User> getUserList() {
        List<User> userList = new ArrayList<>();

        // 3+1
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        // t_users
        String sql = "select * from t_users";

        try {

            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/sctu_javaweb_2018",
                    "root",
                    "123456"
            );

            statement = connection.createStatement();

            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {


                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String password = resultSet.getString(3);

                // 封装
                User user = new User();
                user.setId(id);
                user.setName(name);
                user.setPassword(password);

                userList.add(user);
            }

            resultSet.close();
            statement.close();
            connection.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userList;

    }

    private Connection getConnection() throws SQLException, ClassNotFoundException {
        // 3+1
        Connection connection = null;


        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/sctu_javaweb_2018",
                "root",
                "123456"
        );
        return connection;
    }
}
